package com.karson.common.config.rabbitmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author ZKS
 */
@Component
public class MsgProducer implements RabbitTemplate.ConfirmCallback {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private RabbitTemplate rabbitTemplate;
    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MsgProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 发送消息到指定交换机和路由键
     * @param exchangeName 交换机名称
     * @param routingKey   路由键
     * @param messageObj   消息对象（会自动转为 JSON）
     */
    public void sendMsg(String exchangeName, String routingKey, String messageObj) {
        // 每条消息带唯一 ID，方便确认回调
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());

        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, routingKey, messageObj, correlationId);

        System.out.printf("消息已发送 -> Exchange: %s | RoutingKey: %s | 内容: %s%n",
                exchangeName, routingKey, messageObj);
    }

    /**
     * 广播模式
     * @param content
     */
    public void sendAll(String content) {
        rabbitTemplate.convertAndSend("fanoutExchange","", content);
    }

    /**
     * 回调
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            logger.info("消息成功消费");
        } else {
            logger.info("消息消费失败:" + cause);
        }
    }
}